package com.cloudcc.mobile.parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.cloudcc.mobile.entity.CustomerEntity;
import com.cloudcc.mobile.entity.KeHuMessage;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.Tools;

public class KeHuParser {
	/**
	 * 解析查询的客户
	 * 
	 * @param jsonString
	 * @return
	 */
	public static KeHuMessage getKeHu(String jsonString) {
		ArrayList<CustomerEntity> list = new ArrayList<CustomerEntity>();
		KeHuMessage message = new KeHuMessage();
		try {
			JSONObject obj = new JSONObject(jsonString);
			message.setResult(obj.getBoolean("result"));
			message.setReturnInfo(obj.getString("returnInfo"));
			message.setReturncode(obj.getString("returnCode"));
			message.setTotalCount(obj.getInt("totalCount"));
			message.setPageNUM(obj.getInt("pageNUM"));
			message.setPageSize(obj.getInt("pageSize"));
			message.setPageCount(obj.getInt("pageCount"));
			message.setHaspre(obj.getBoolean("hasPre"));
			message.setHasnext(obj.getBoolean("hasNext"));
			JSONArray json = obj.getJSONArray("data");
			for (int i = 0; i < json.length(); i++) {
				JSONObject jsonObj = json.getJSONObject(i);
				CustomerEntity kehu = (CustomerEntity) Json.toObject(
						jsonObj.toString(), CustomerEntity.class);
				list.add(kehu);
			}
			message.setList(list);
		} catch (JSONException e) {
			Tools.handle(e);
		}
		return message;
	}

	/**
	 * 获取所有客户
	 * 
	 */

	public static Map<String, CustomerEntity> getAllCallRecords(
			Context context, String jsonString) {
		KeHuMessage kehuMessage = getKeHu(jsonString);
		if (!kehuMessage.isResult()) {
			return null;
		}
		List<CustomerEntity> kehu = kehuMessage.getList();
		Map<String, CustomerEntity> map = new HashMap<String, CustomerEntity>();
		if (kehu != null) {
			for (int i = 0; i < kehu.size(); i++) {
				String name = kehu.get(i).getName();
				map.put(name, kehu.get(i));
			}
			return map;
		}
		return null;
	}

	/**
	 * 解析"带权限"插入返回数据
	 */
	public static boolean getResult(String jsonString) {
		boolean result = false;
		try {
			JSONObject obj = new JSONObject(jsonString);
			result = obj.getBoolean("result");
		} catch (JSONException e) {
			Tools.handle(e);
		}
		return result;
	}

	/**
	 * 解析修改返回数据
	 */
	public static boolean getUpResult(String jsonString) {
		boolean result = false;
		try {
			JSONObject obj = new JSONObject(jsonString);
			result = obj.getBoolean("result");
		} catch (Exception e) {
			Tools.handle(e);
		}
		return result;
	}
}
